package com.ag.lwc.dao;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.ag.bean.TbEventInfect;
import com.ag.bean.TbIds;
import com.ag.bean.TbTarget;
import com.ag.common.IDUtil;
import com.ag.dao.TbEventInfectDAO;
import com.ag.dao.TbTargetDAO;

public class MyTbTargetDAO extends TbTargetDAO {
	private static final Log log = LogFactory.getLog(TbTarget.class);
	public List<TbTarget> find(String eventId){
		List<TbTarget> result = null;
		Session session = this.getSessionFactory().openSession();
		Query query = session.createQuery("from TbTarget t left join fetch t.tbEvent e where e.EId =:eventId order by t.TId").setString("eventId", eventId);
		result = query.list();
		session.close();
		return result;
		
	}
	public void delete(String TId)								//根据Id删除影响范围
	{
		Session session = this.getSessionFactory().openSession();
		Transaction ctx = session.getTransaction();
		try
		{
			session.beginTransaction();
			session.createQuery("delete from TbTarget e where e.TId =:TId").setString("TId", TId).executeUpdate();
			ctx.commit();
			log.debug("delete TbTarget successful");
		}catch(RuntimeException re)
		{
			ctx.rollback();
			log.error("delete failed", re);
		}
		session.close();
	}
	public void save(TbTarget target)				//新增事件的影响范围
	{
		if(target.getTbEvent()==null||target.getTbEvent().getEId()==null) 
			{System.out.println("***************dao: 防控目标的事件不存在***********************");return;}
		System.out.println("************************dao: 事件id: "+target.getTbEvent().getEId()+"*************************");
		IDUtil idutil = null;
		TbIds myId = null;
		Session session = this.getSessionFactory().openSession();
		Transaction ctx = session.getTransaction();
		log.debug("saving TbEventInfect instance");
		try
		{		
		session.beginTransaction();								
		//1.形成主键
		String tablePK=null;
		List<String> list = session.createQuery("select max(c.TId) from TbTarget c").list();
	
		if(list.get(0)!=null)
		  {
			tablePK=list.get(0);System.out.println("********************dao:tableKey： "+tablePK+"****************************");
		    Long tmp = Long.valueOf(tablePK);
			tablePK = (++tmp).toString();	
		  }
		
		else tablePK="1000000001";				
		target.setTId(tablePK);	
		target.setA(IDUtil.PRESERVE);
		//2.维护id管理表
		myId=(TbIds) session.get(TbIds.class, IDUtil.TB_TARGET);
		if(myId == null)
		{
			//myId = new TbIds(idutil.TB_TARGET,tablePK);myId.setIdValues(tablePK);	
			myId = new TbIds((int)idutil.TB_TARGET,tablePK);myId.setIdValues(tablePK);	
			session.save(myId);
		}
		myId.setIdValues(tablePK);						
		session.save(target);
		ctx.commit();
		log.debug("delete TbEventInfect successful");
		}catch(RuntimeException re)
		{
			ctx.rollback();
			log.error("delete failed", re);
		}
		session.close();
	}
}
